<?php

namespace App\Task;

use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\DataSpread;
use App\Model\DataUserJuliangTokenRel;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\SystemOrderDay;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;


//#[Crontab(name: "backhaulOrderTask", rule: "*/30 * * * * *", callback: "execute", memo: "回传上报订单'")]
//#[Crontab(name: "SpreaduploadTask", rule: "1 * * * *", callback: "execute", memo: "发送推广链接到统计后台'")]
class SpreaduploadTask
{
    protected LoggerInterface $logger;

    public static $upSpreadLink = "https://novel.kuaiyingbox.com/api/spread";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'SpreaduploadTask');
    }

    public function execute()
    {

        $endTime = date('Y-m-d H:i:s',time());
        $startTime = date('Y-m-d H:i:s',time()-7200);

        try {
            $this->logger->info(date('Y-m-d H:i:s') . '------------------------获得数据');
            $spread = DataSpread::query()
                ->select(['data_spread.*','playlet.name as playlet_name','system_user.real_name as user_name'])
                ->leftJoin('system_user','data_spread.user_id','=','system_user.id')
                ->leftJoin('playlet','data_spread.playlet_id','=','playlet.id')
//                ->limit(1000)
                ->whereBetween('data_spread.created_at',[$startTime,$endTime])
                ->orderBy('data_spread.id')->get()->toArray();
            $count = count($spread);
            $this->logger->info(date('Y-m-d H:i:s') . '------------------------上传推广数据：',[$count]);
            if(!empty($spread)){
                 $this->uploadspread($spread);
            }
        }catch (\Exception $e){
            $this->logger->error('请求|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取数据');
    }
    public function uploadspread($params){
        $postparams = [
            'data' => $params
        ];
        $taskUrl = self::$upSpreadLink;
        $this->logger->info('上传推广链接Url：'.$taskUrl);
        $this->logger->info('上传推广链接数据：'.PHP_EOL.var_export(['result' => $postparams], true));
        //开始上传
        $postResult  = $this->json_post($taskUrl,$postparams);
        $this->logger->info('上传推广链接详情接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        return true;

    }
    /**
     * 传入数组进行HTTP POST请求
     */
    private function json_post($url, $data = NULL)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

}